package com.example.springbootshiro.service.impl;

import com.example.springbootshiro.dao.PermissionDao;
import com.example.springbootshiro.dao.RoleDao;
import com.example.springbootshiro.dao.UserDao;
import com.example.springbootshiro.model.Permission;
import com.example.springbootshiro.model.Role;
import com.example.springbootshiro.model.User;
import com.example.springbootshiro.response.BusinessError;
import com.example.springbootshiro.service.UserService;
import com.example.springbootshiro.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Created by YangGang on 2021/12/15 10:58。
 */
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserDao userDao;
    @Autowired
    RoleDao roleDao;
    @Autowired
    PermissionDao permissionDao;

    @Override
    public User findUserByUsername(String username) {
        return userDao.selectByUsername(username);
    }

    @Override
    public List<Role> findUserRolesByUsername(String username) {
        return roleDao.listByUsername(username);
    }

    @Override
    public List<Permission> findUserPermissionsByUsername(String username) {
        return permissionDao.listByUsername(username);
    }

    @Override
    @Transactional
    public int addUser(User user) {
        //对密码进行 md5+salt 加密处理
        String salt = PasswordUtil.getSalt(8);
        String passMd5 = PasswordUtil.md5AndSalt(user.getPassword(), salt);
        user.setPassword(passMd5);
        user.setSalt(salt);
        int i = userDao.insertSelective(user);
        /*if ("t99".equals(user.getUsername())) {
            throw new BusinessError("测试事物");
        }*/
        return i;
    }
}
